package face.business;

import java.util.List;

import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_core.RectVector;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.OpenCVFrameConverter;

import com.google.common.collect.Lists;

import face.entity.Face;
import face.service.GetUserInfoService;
import face.util.CheckFaceAndEye;
import face.util.FaceList;
import face.util.IdentityPeople;
import face.util.FaceAndEyeToos;
/**
 * 检测摄像头是否有人出现
 * @author ShiQiang
 *
 */
public class CameraFaceInfo {
	/**
	 * 从摄像头获取图片
	 * @param frame
	 * @param time
	 */
	static OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
	static long begin = System.currentTimeMillis();
	
	public synchronized static Frame dealTheMat(Frame frame){ 
		 
		
		 
		//图像转换
		Mat mat = f2M(frame);
		 
		System.out.println("====3进行面部识别====");
		//检测是否有人员
		RectVector faces = CheckFaceAndEye.findFaces(mat);
		//不存在则直接返回
		if(faces == null){
			return m2F(mat);
		}
		System.out.println("====4进行人员查找====");
		//如果存在则判断是否是会员
		
		List<Face> peoples = IdentityPeople.findPeople(mat, faces);
		System.out.println("====5无相关人员操作====");
		if(peoples.isEmpty()){ 
			 
			//保存陌生人
			FaceAndEyeToos.saveFace(faces, mat, false);  
			//对图像进行标记
			//SaveImage.drawCircleEye(faces, mat); 
			//SaveImage.drawRectangleFace(faces, mat);  
			FaceAndEyeToos.saveOriFace(mat);
			//重新加载人脸信息
			FaceList.loadFaceFile();
			//重新训练
			IdentityPeople.train();
			return m2F(mat);
		}
		List<String> msg = Lists.newArrayList();
		for(Face face : peoples){
			GetUserInfoService info = new GetUserInfoService();
			msg.add(info.getById(face.getId()).getName());
		}
		
		FaceAndEyeToos.drawCircleEye(faces, mat); 
		FaceAndEyeToos.drawRectangleFace(faces, mat);  
		
		if(!msg.isEmpty()){
			mat = FaceAndEyeToos.putMsg(faces, mat, msg); 
		}
		
		
		//1发送信息给管理员
		//2放置查询信息到mat中显示
		
		return m2F(mat);
	} 
	
	/**
	 * 数据类型转换 Frame to Mat
	 * @param img
	 * @return
	 */
	public static Mat f2M(Frame img){
		return converter.convertToMat(img);
	} 
	
	/**
	 * 数据类型转换 Mat to Frame
	 * @param img
	 * @return
	 */
	public static Frame m2F(Mat img){
		return converter.convert(img);
	}
}
